<?php
// FastPHP 框架核心公共函数
// 只加载一次
if (defined('__FASTPHP_COMMON_LOADED__')) return;
define('__FASTPHP_COMMON_LOADED__', 1);

require_once ROOT_PATH . 'FastPHP/Library/Request.php';
require_once ROOT_PATH . 'FastPHP/Library/Response.php';
require_once ROOT_PATH . 'FastPHP/Library/Cache.php';

// -------------------- 请求相关 --------------------
/**
 * 获取Request对象单例
 * @return \FastPHP\Library\Request
 */
function request()
{
    return \FastPHP\Library\Request::instance();
}

// -------------------- 响应相关 --------------------
/**
 * 获取Response对象实例
 * @return \FastPHP\Library\Response
 */
function response()
{
    static $instance;
    if (!$instance) {
        $instance = new \FastPHP\Library\Response();
    }
    return $instance;
}

// -------------------- 缓存相关 --------------------
/**
 * 缓存助手函数
 * 用法：cache('key')/cache('key', 'val')/cache('key', null) 删除
 * @param string $key
 * @param mixed $value
 * @param array $options
 * @return mixed
 */
function cache($key, $value = '[__NOT_SET__]', $options = [])
{
    if ($value === '[__NOT_SET__]') {
        return \FastPHP\Library\Cache::get($key, null, $options['store'] ?? null);
    } elseif ($value === null) {
        return \FastPHP\Library\Cache::delete($key, $options['store'] ?? null);
    } else {
        $expire = $options['expire'] ?? null;
        return \FastPHP\Library\Cache::set($key, $value, $expire, $options['store'] ?? null);
    }
}

// -------------------- 配置相关 --------------------
/**
 * 获取配置项
 * 用法：config('app.debug') / config('database.host') / config('app')
 * @param string $key 配置键，支持点语法
 * @param mixed $default 默认值
 * @return mixed
 */
function config($key = null, $default = null)
{
    static $configs = [];
    
    // 如果key为空，返回所有配置
    if ($key === null) {
        return $configs;
    }
    
    $parts = explode('.', $key);
    $configFile = array_shift($parts);
    
    // 如果配置未加载，则加载配置
    if (!isset($configs[$configFile])) {
        $configPath = ROOT_PATH . 'config/' . $configFile . '.php';
        if (file_exists($configPath)) {
            $configs[$configFile] = require $configPath;
        } else {
            return $default;
        }
    }
    
    $config = $configs[$configFile];
    
    // 如果没有子键，返回整个配置
    if (empty($parts)) {
        return $config;
    }
    
    // 遍历子键
    foreach ($parts as $part) {
        if (isset($config[$part])) {
            $config = $config[$part];
        } else {
            return $default;
        }
    }
    
    return $config;
}

// -------------------- 模型/URL/输入/跳转/时间 --------------------
/**
 * 快速实例化模型
 * @param string $name
 * @return object
 */
function model($name)
{
    $class = APP_GROUP . '\\app\\model\\' . ucfirst($name);
    if (class_exists($class)) {
        return new $class();
    }
    throw new Exception("模型 {$class} 不存在");
}

/**
 * 生成URL
 * @param string $route 例如 Index/index
 * @param array $params 额外参数
 * @param string $suffix 后缀
 * @return string
 */
function url($route, $params = [], $suffix = null)
{
    $parts = explode('/', $route);
    $group = defined('APP_GROUP') ? APP_GROUP : (isset($_GET['s']) ? $_GET['s'] : 'home');
    $controller = $parts[0] ?? 'Index';
    $action = $parts[1] ?? 'index';
    $url = "/index.php/{$group}/{$controller}/{$action}";
    foreach ($params as $k => $v) {
        $url .= "/{$k}/{$v}";
    }
    if ($suffix === null) {
        $suffix = config('app.route.suffix', 'html');
    }
    if ($suffix) {
        $url .= ".{$suffix}";
    }
    return $url;
}

/**
 * 判断是否POST请求
 */
function is_post()
{
    return $_SERVER['REQUEST_METHOD'] === 'POST';
}

/**
 * 判断是否GET请求
 */
function is_get()
{
    return $_SERVER['REQUEST_METHOD'] === 'GET';
}

/**
 * 获取输入参数
 * @param string $name
 * @param mixed $default
 * @param string $method
 * @return mixed
 */
function input($name, $default = null, $method = null)
{
    $source = $_REQUEST;
    if ($method === 'get') $source = $_GET;
    if ($method === 'post') $source = $_POST;
    return isset($source[$name]) ? $source[$name] : $default;
}

/**
 * 跳转
 * @param string $url
 * @param int $code
 */
function redirect($url, $code = 302)
{
    header("Location: $url", true, $code);
    exit;
}

/**
 * 当前时间
 * @return string
 */
function fp_now()
{
    return date('Y-m-d H:i:s');
}

// -------------------- 分页相关 --------------------
/**
 * 创建分页实例
 * @param int $total 总记录数
 * @param int $perPage 每页记录数
 * @param int $currentPage 当前页码
 * @param array $config 配置参数
 * @return \FastPHP\Library\Paginator
 */
function paginator($total, $perPage = 10, $currentPage = 1, $config = [])
{
    return \FastPHP\Library\Paginator::make($total, $perPage, $currentPage, $config);
} 